﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace _4._06将EAP模式转换为任务
{
    class Program
    {
        private static int TaskMethod(string name, int seconds)
        {
            Console.WriteLine($"Task{name} is running on a thread id {Thread.CurrentThread.ManagedThreadId}. Is thread pool thread: {Thread.CurrentThread.IsThreadPoolThread}");
            Thread.Sleep(TimeSpan.FromSeconds(seconds));
            return 42 * seconds;
        }

        static void Main(string[] args)
        {
            var tcs = new TaskCompletionSource<int>();
            var worker = new BackgroundWorker();
            worker.DoWork += (sender, eventArgs) =>
            {
                eventArgs.Result = TaskMethod("Background workers", 5);
            };
            worker.RunWorkerCompleted += (sender, eventArgs) =>
            {
                if (eventArgs.Error != null) tcs.SetException(eventArgs.Error);
                else if (eventArgs.Cancelled) tcs.SetCanceled();
                else tcs.SetResult((int)eventArgs.Result);
            };

            worker.RunWorkerAsync();
            Console.WriteLine($"Result is: {tcs.Task.Result}");
            Console.ReadLine();
        }
    }
}
